package com.lh.sms.listener;

import com.aliyuncs.CommonResponse;
import com.lh.sms.conf.SmsProperties;
import com.lh.sms.utils.SmsUtils;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 短信发送监听
 *
 * @author liuhe
 * @date 2020/07/02
 */
@Component
@EnableConfigurationProperties(SmsProperties.class)
public class SmsListener {
    private final SmsUtils smsUtils;
    private final SmsProperties smsProperties;

    public SmsListener(SmsUtils smsUtils, SmsProperties smsProperties) {
        this.smsUtils = smsUtils;
        this.smsProperties = smsProperties;
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "leyou.sms.queue", durable = "true"),
            exchange = @Exchange(value = "leyou.sms.exchange", ignoreDeclarationExceptions = "true"),
            key = {"sms.verify.code"}
    ))
    public void listenSms(Map<String, String> msg) {
        if (CollectionUtils.isEmpty(msg)) {
            // 放弃处理
            return;
        }
        String phone = msg.get("phone");
        String code = msg.get("code");

        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            // 放弃处理
            return;
        }
        String signName = msg.get("signName");
        String templateCode = msg.get("templateCode");
        // 发送消息
        CommonResponse commonResponse = this.smsUtils.sendSms(phone, code,
                StringUtils.isEmpty(signName) ? smsProperties.getSignName() : signName,
                StringUtils.isEmpty(templateCode) ? smsProperties.getVerifyCodeTemplate() : templateCode);
    }
}
